{
 "cells": [
  {
   "cell_type": "raw",
   "id": "fd2f990f",
   "metadata": {},
   "source": [
    "---\n",
    "skip_showdoc: true\n",
    "skip_exec: true\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e79b101a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp stripe_otp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "215df754",
   "metadata": {},
   "source": [
    "# Stripe"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8813452",
   "metadata": {},
   "source": [
    "This guide will walk through a minimal example of working with a Stripe one-time payment link and webhook for secure reconciliation of payments.\n",
    "\n",
    "To get started we can import the stripe library and authenticate with a **Stripe API key** that you can get from the stripe web UI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3570a68b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "from fasthtml.common import *\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc428f2e",
   "metadata": {},
   "source": [
    "## Stripe Authentication"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "780b79de",
   "metadata": {},
   "source": [
    "You can install stripe python sdk directly from pypi:\n",
    "\n",
    "```sh\n",
    "pip install stripe\n",
    "```\n",
    "\n",
    "Additionally, you need to install the stripe cli. You can find how to install it on your specific system in their docs [here](https://docs.stripe.com/get-started/development-environment?lang=python#setup-cli)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aba5674f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# uncomment and execute if needed\n",
    "#!pip install stripe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8053cd4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "import stripe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a2b99a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "stripe.api_key = os.environ.get(\"STRIPE_SECRET_KEY\")\n",
    "DOMAIN_URL = os.environ.get(\"DOMAIN_URL\", \"http://localhost:5001\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a48b90ec",
   "metadata": {},
   "source": [
    "You can get this API key from the Stripe Dashboard by going to [this url](https://dashboard.stripe.com/test/apikeys).\n",
    "\n",
    "\n",
    ":::{.callout-note}\n",
    "\n",
    "Note: Make sure you have `Test mode` turned on in the dashboard.\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6fc556ba",
   "metadata": {},
   "source": [
    "![](StripeDashboard_API_Key.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee5dcc87",
   "metadata": {},
   "source": [
    "Make sure you are using a test key for this tutorial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "932640d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert 'test_' in stripe.api_key"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d8d7745",
   "metadata": {},
   "source": [
    "## Pre-app setup\n",
    "\n",
    ":::{.callout-tip}\n",
    "Everything in the pre-app setup sections is a run once and not to be included in your web-app.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bb9711e",
   "metadata": {},
   "source": [
    "### Create a product"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "086e35e0",
   "metadata": {},
   "source": [
    "You can run this to programatically create a Stripe **Product** with a **Price**.  Typically, this is not something you do dynamically in your FastHTML app, but rather something you set up one time.  You can also optionally do this on the Stripe Dashboard UI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54d779e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "def _search_app(app_nm:str, limit=1): \n",
    "    \"Checks for product based on app_nm and returns the product if it exists\"\n",
    "    return stripe.Product.search(query=f\"name:'{app_nm}' AND active:'True'\", limit=limit).data\n",
    "\n",
    "def create_price(app_nm:str, amt:int, currency=\"usd\") -> list[stripe.Price]:\n",
    "    \"Create a product and bind it to a price object. If product already exist just return the price list.\"\n",
    "    existing_product = _search_app(app_nm)\n",
    "    if existing_product: \n",
    "        return stripe.Price.list(product=existing_product[0].id).data\n",
    "    else:\n",
    "        product = stripe.Product.create(name=f\"{app_nm}\")\n",
    "        return [stripe.Price.create(product=product.id, unit_amount=amt, currency=currency)]\n",
    "\n",
    "def archive_price(app_nm:str):\n",
    "    \"Archive a price - useful for cleanup if testing.\"\n",
    "    existing_products = _search_app(app_nm, limit=50)\n",
    "    for product in existing_products:\n",
    "        for price in stripe.Price.list(product=product.id).data: \n",
    "            stripe.Price.modify(price.id, active=False)\n",
    "        stripe.Product.modify(product.id, active=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a44c7664",
   "metadata": {},
   "source": [
    ":::{.callout-tip}\n",
    "\n",
    "To do recurring payment, you would use `recurring={\"interval\": \"year\"}` or `recurring={\"interval\": \"month\"}` when creating your stripe price.\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4455b7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "app_nm = \"[FastHTML Docs] Demo Product\"\n",
    "price_list = create_price(app_nm, amt=1999)\n",
    "assert len(price_list) == 1, 'For this tutorial, we only have one price bound to our product.'\n",
    "price = price_list[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a78b390",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Price ID = price_1R1ZzcFrdmWPkpOp9M28ykjy\n"
     ]
    }
   ],
   "source": [
    "print(f\"Price ID = {price.id}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a0fff42",
   "metadata": {},
   "source": [
    "### Create a webook"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8781b7a2",
   "metadata": {},
   "source": [
    "A webhook is simply a URL where your app listens for messages from Stripe. It provides a way for Stripe, the payment processor, to notify your application when something happens with a payment. Think of it like a delivery notification: when a customer completes a payment, Stripe needs to tell your application so you can update your records, send confirmation emails, or provide access to purchased content. It is simply a URL, \n",
    "\n",
    "But your app needs to be sure every webhook event is actually coming from Stripe. That is, it needs to authenticate the notification. To do that, your app will need a **webhook signing secret**, which it uses to confirm that the notifications were signed by Stripe.\n",
    "\n",
    "This secret is different from your Stripe API key. The Stripe API key lets you prove who you are to Stripe. The webhook signing secret lets you be sure messages from Stripe are coming from Stripe.\n",
    "\n",
    "You will need a webhook signing secret whether your app is is running locally in test mode, or whether it is a real production app on running on a server. Here is how you get the webhook signing secret in these two cases."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f629661",
   "metadata": {},
   "source": [
    "#### Local Webhook"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44dea9f8",
   "metadata": {},
   "source": [
    "When your application runs locally during development it can be reached only from your computer, so Stripe can't make an HTTP request against the webhook. To workaround this in development, the Stripe CLI tool creates a secure tunnel which forwards these webhook notifications from Stripe's servers to your local application. \n",
    "\n",
    "Run this command to start that tunnel:\n",
    "\n",
    "```bash\n",
    "stripe listen --forward-to http://localhost:5001/webhook\n",
    "```\n",
    "\n",
    "On success, that command will also tell you the webhook signing secret. Take the secret it gives you and set it as an environment variable.\n",
    "\n",
    "```bash\n",
    "export STRIPE_LOCAL_TEST_WEBHOOK_SECRET=<your-secret>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd79ac5f",
   "metadata": {},
   "source": [
    "#### Production Webhook"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "569793f5",
   "metadata": {},
   "source": [
    "For a deployed app, you configure a permanent webhook connection in your Stripe Dashboard. This establishes an official notification channel where Stripe will send real-time updates about payments to your application's `/webhook` URL.\n",
    "\n",
    "On the dashboard, you can configure which specific payment event notifications will go to this webhook (e.g., completed checkouts, successful payments, failed payments, etc..). Your app provides the webhook signing secret to the Stripe library, to authenticate that these notifications come from the Stripe service. This is essential for production environments where your app needs to automatically respond to payment activities without manual intervention.\n",
    "\n",
    "To configure the permanent webhook connection, you need to do the following steps:\n",
    "\n",
    "1. Make sure you are in Test mode like before\n",
    "1. Go to https://dashboard.stripe.com/test/webhooks\n",
    "1. Click \"+ Add endpoint\" to create create a new webhook (or, if that is missing, click \"Create an event destination\").\n",
    "\n",
    "1. On the primary screen shown below, \"Listen to Stripe events\", fill out the details. Your Endpoint URL will be `https://YOURDOMAIN/webhook`\n",
    "\n",
    "1. Save your webhook signing scret. On the \"Listen to Stripe events\" screen, you can find it in the app sample code on the right hand side as the \"endpoint secret\". You can also retrieve it later from the dashboard.\n",
    "\n",
    "![](CreateWebhook.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "582341e7",
   "metadata": {},
   "source": [
    "You also need to configure which events should generate webhook notifications:\n",
    "\n",
    "1. Click \"+ Select events\" to open the secondary control screen, \"Select events to send\", which is shown below. In on our case we want to listen for `checkout.session.completed`.\n",
    "\n",
    "1. Click the \"Add Events\" button, to confirm which events to send.\n",
    "\n",
    "![](CreateWebhook2.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42917e5b",
   "metadata": {},
   "source": [
    ":::{.callout-tip}\n",
    "            \n",
    "For subscriptions you may also want to enable additional events for your webhook such as:\n",
    "`customer.subscription.created`, `customer.subscription.deleted`, and others based on your use-case.\n",
    "\n",
    "![](SubscriptionEvents.png)\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8312e8f",
   "metadata": {},
   "source": [
    "Finally, click \"Add Endpoint\", to finish configuring the endpoint.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61c07ab8",
   "metadata": {},
   "source": [
    "## App"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e9e47c9",
   "metadata": {},
   "source": [
    ":::{.callout-tip}\n",
    "Everything after this point is going to be included in your actual application.  The application created in this tutorial can be found [here](https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/explains/stripe_otp.py)\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a66f891",
   "metadata": {},
   "source": [
    "### Setup to have the right information"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24656d60",
   "metadata": {},
   "source": [
    "In order to accept a payment, you need to know who is making the payment.\n",
    "\n",
    "There are many ways to accomplish this, for example using [oauth](https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/explains/oauth.ipynb) or a form.  For this example we will start by hardcoding an email address into  a session to simulate what it would look like with oauth.\n",
    "\n",
    "We save the email address into the session object, under the key `auth`. By putting this  logic into beforeware, which runs before every request is processed, we ensure that every route handler will be able to read that address from the session object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32440b4c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "def before(sess): sess['auth'] = 'hamel@hamel.com'\n",
    "bware = Beforeware(before, skip=['/webhook'])\n",
    "app, rt = fast_app(before=bware)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f2fb430",
   "metadata": {},
   "source": [
    "We will need our webhook secret that was created.  For this tutorial, we will be using the local development environment variable that was created above.  For your deployed production environment, you will need to get the secret for your webhook from the Stripe Dashboard."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5459425",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "WEBHOOK_SECRET = os.getenv(\"STRIPE_LOCAL_TEST_WEBHOOK_SECRET\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b6cc813",
   "metadata": {},
   "source": [
    "### Payment Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bceec10",
   "metadata": {},
   "source": [
    "We need 2 things first:\n",
    "\n",
    "1. A button for users to click to pay\n",
    "1. A route that gives stripe the information it needs to process the payment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9924a82",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "@rt(\"/\")\n",
    "def home(sess):\n",
    "    auth = sess['auth']\n",
    "    return Titled(\n",
    "        \"Buy Now\", \n",
    "        Div(H2(\"Demo Product - $19.99\"),\n",
    "            P(f\"Welcome, {auth}\"),\n",
    "            Button(\"Buy Now\", hx_post=\"/create-checkout-session\", hx_swap=\"none\"),\n",
    "            A(\"View Account\", href=\"/account\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2cc72784",
   "metadata": {},
   "source": [
    "We are only allowing card payments (`payment_method_types=['card']`).  For additional options see the [Stripe docs](https://docs.stripe.com/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d7594b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "@rt(\"/create-checkout-session\", methods=[\"POST\"])\n",
    "async def create_checkout_session(sess):\n",
    "    checkout_session = stripe.checkout.Session.create(\n",
    "        line_items=[{'price': price.id, 'quantity': 1}],\n",
    "        mode='payment',\n",
    "        payment_method_types=['card'],\n",
    "        customer_email=sess['auth'],\n",
    "        metadata={'app_name': app_nm, \n",
    "                  'AnyOther': 'Metadata',},\n",
    "        # CHECKOUT_SESSION_ID is a special variable Stripe fills in for you\n",
    "        success_url=DOMAIN_URL + '/success?checkout_sid={CHECKOUT_SESSION_ID}',\n",
    "        cancel_url=DOMAIN_URL + '/cancel')\n",
    "    return Redirect(checkout_session.url)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "198d7818",
   "metadata": {},
   "source": [
    ":::{.callout-tip}\n",
    "For subscriptions the mode would typically be `subscription` instead of `payment`\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f243397a",
   "metadata": {},
   "source": [
    "This section creates two key components: a simple webpage with a \"Buy Now\" button, and a function that handles what happens when that button is clicked. \n",
    "\n",
    "When a customer clicks \"Buy Now,\" the app creates a Stripe checkout session (essentially a payment page) with product details, price, and customer information. Stripe then takes over the payment process, showing the customer a secure payment form. After payment is completed or canceled, Stripe redirects the customer back to your app using the success or cancel URLs you specified. This approach keeps sensitive payment details off your server, as Stripe handles the actual transaction."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cb9ee93",
   "metadata": {},
   "source": [
    "### Post-Payment Processing\n",
    "\n",
    "After a customer initiates payment, there are two parallel processes:\n",
    "\n",
    "1. **User Experience Flow**: The customer is redirected to Stripe's checkout page, completes payment, and is then redirected back to your application (either the success or cancel page).\n",
    "\n",
    "2. **Backend Processing Flow**: Stripe sends webhook notifications to your server about payment events, allowing your application to update records, provision access, or trigger other business logic.\n",
    "\n",
    "This dual-track approach ensures both a smooth user experience and reliable payment processing.\n",
    "\n",
    "The webhook notification is critical as it's a reliable way to confirm payment completion."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc004fcb",
   "metadata": {},
   "source": [
    "#### Backend Processing Flow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39bddcdc",
   "metadata": {},
   "source": [
    "Create a database schema with the information you'd like to store."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad490552",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "# Database Table\n",
    "class Payment:\n",
    "    checkout_session_id: str  # Stripe checkout session ID (primary key)\n",
    "    email: str\n",
    "    amount: int  # Amount paid in cents\n",
    "    payment_status: str  # paid, pending, failed\n",
    "    created_at: int # Unix timestamp\n",
    "    metadata: str  # Additional payment metadata as JSON"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5efb798",
   "metadata": {},
   "source": [
    "Connect to the database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "649c1de2",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "db = Database(\"stripe_payments.db\")\n",
    "payments = db.create(Payment, pk='checkout_session_id', transform=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c978053",
   "metadata": {},
   "source": [
    "In our webhook we can execute any business logic and database updating we need to."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41b36e3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "@rt(\"/webhook\")\n",
    "async def post(req):\n",
    "    payload = await req.body()\n",
    "    # Verify the event came from Stripe\n",
    "    try:\n",
    "        event = stripe.Webhook.construct_event(\n",
    "            payload, req.headers.get(\"stripe-signature\"), WEBHOOK_SECRET)\n",
    "    except Exception as e:\n",
    "        print(f\"Webhook error: {e}\")\n",
    "        return\n",
    "    if event and event.type == \"checkout.session.completed\":\n",
    "        event_data = event.data.object\n",
    "        if event_data.metadata.get('app_name') == app_nm:\n",
    "            payment = Payment(\n",
    "                checkout_session_id=event_data.id,\n",
    "                email=event_data.customer_email,\n",
    "                amount=event_data.amount_total,\n",
    "                payment_status=event_data.payment_status,\n",
    "                created_at=event_data.created,\n",
    "                metadata=str(event_data.metadata))\n",
    "            payments.insert(payment)\n",
    "            print(f\"Payment recorded for user: {event_data.customer_email}\")\n",
    "            \n",
    "    # Do not worry about refunds yet, we will cover how to do this later in the tutorial\n",
    "    elif event and event.type == \"charge.refunded\":\n",
    "        event_data = event.data.object\n",
    "        payment_intent_id = event_data.payment_intent\n",
    "        sessions = stripe.checkout.Session.list(payment_intent=payment_intent_id)\n",
    "        if sessions and sessions.data:\n",
    "            checkout_sid = sessions.data[0].id\n",
    "            payments.update(Payment(checkout_session_id= checkout_sid, payment_status=\"refunded\"))\n",
    "            print(f\"Refund recorded for payment: {checkout_sid}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e221d49",
   "metadata": {},
   "source": [
    "The webhook route is where Stripe sends automated notifications about payment events. When a payment is completed, Stripe sends a secure notification to this endpoint. The code verifies this notification is legitimate using the webhook secret, then processes the event data - extracting information like the customer's email and payment status. This allows your application to automatically update user accounts, trigger fulfillment processes, or record transaction details without manual intervention.\n",
    "\n",
    "Note that in this route, our code extracts the user's email address from the Stripe event, _not from the session object_. That is the because this route will be hit by a request from Stripe's servers, not from the user's browser."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c67f2b7",
   "metadata": {},
   "source": [
    ":::{.callout-tip}\n",
    "When doing a subscription, often you would add additional event types in an if statement to update your database appropriately with the subscription status.\n",
    "\n",
    "```python\n",
    "if event.type == \"payment_intent.succeeded\":\n",
    "    ...\n",
    "elif event.type == \"customer.subscription.created\":\n",
    "    ...\n",
    "elif event.type == \"customer.subscription.deleted\":\n",
    "    ...\n",
    "```\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e988e9e4",
   "metadata": {},
   "source": [
    "#### User Experience Flow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec0a4636",
   "metadata": {},
   "source": [
    "The `/success` route is where Stripe will redirect the user *after* the payment completes successfully, which will also be after Stripe has called the webhook to inform your app of the transaction.\n",
    "\n",
    "Stripe knows to send the user here, because you provided Stripe with this route when you created a checkout session.\n",
    "\n",
    "But you want to verify this is the case. So in this route, you should verify the user's payment status, by checking your database for the entry which your app saved when it received that webhook notification."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea17a1bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "@rt(\"/success\")\n",
    "def success(sess, checkout_sid:str):    \n",
    "    # Get payment record from database (saved in the webhook)\n",
    "    payment = payments[checkout_sid]\n",
    "\n",
    "    if not payment or payment.payment_status != 'paid': \n",
    "        return Titled(\"Error\", P(\"Payment not found\"))\n",
    "\n",
    "    return Titled(\n",
    "        \"Success\",\n",
    "        Div(H2(\"Payment Successful!\"),\n",
    "            P(f\"Thank you for your purchase, {sess['auth']}\"),\n",
    "            P(f\"Amount Paid: ${payment.amount / 100:.2f}\"),\n",
    "            P(f\"Status: {payment.payment_status}\"),\n",
    "            P(f\"Transaction ID: {payment.checkout_session_id}\"),\n",
    "            A(\"Back to Home\", href=\"/\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec55080a",
   "metadata": {},
   "source": [
    "There is also a `/cancel` route, where Stripe will redirect the user if they canceled the checkout."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ca941f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "@rt(\"/cancel\")\n",
    "def cancel():\n",
    "    return Titled(\n",
    "        \"Cancelled\",\n",
    "        Div(H2(\"Payment Cancelled\"),\n",
    "            P(\"Your payment was cancelled.\"),\n",
    "            A(\"Back to Home\", href=\"/\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9cb3f17f",
   "metadata": {},
   "source": [
    "This image shows Stripe's payment page that customers see after clicking the \"Buy Now\" button. When your app redirects to the Stripe checkout URL, Stripe displays this secure payment form where customers enter their card details. For testing purposes, you can use Stripe's test card number (4242 4242 4242 4242) with any future expiration date and any 3-digit CVC code. This test card will successfully process payments in test mode without charging real money. The form shows the product name and price that were configured in your Stripe session, providing a seamless transition from your app to the payment processor and back again after completion."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f7504b6",
   "metadata": {},
   "source": [
    "![](StripePaymentPage.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "044a4294",
   "metadata": {},
   "source": [
    "Once you have processed the payments you can see each record in the sqlite database that was stored in the webhook."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e792a4a",
   "metadata": {},
   "source": [
    "Next, we can see how to add the refund route"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1389a23",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "@rt(\"/refund\", methods=[\"POST\"])\n",
    "async def refund(sess, checkout_sid:str):\n",
    "    # Get payment record from database\n",
    "    payment = payments[checkout_sid]\n",
    "    \n",
    "    if not payment or payment.payment_status != 'paid':\n",
    "        return P(\"Error: Payment not found or not eligible for refund\")\n",
    "    \n",
    "    try:\n",
    "        # Get the payment intent ID from the checkout session\n",
    "        checkout_session = stripe.checkout.Session.retrieve(checkout_sid)\n",
    "        \n",
    "        # Process the refund\n",
    "        refund = stripe.Refund.create(payment_intent=checkout_session.payment_intent, reason=\"requested_by_customer\")\n",
    "        \n",
    "        # Update payment status in database\n",
    "        payments.update(Payment(checkout_session_id= checkout_sid, payment_status=\"refunded\"))\n",
    "        \n",
    "        return Div(\n",
    "            P(\"Refund processed successfully!\"),\n",
    "            P(f\"Refund ID: {refund.id}\"))\n",
    "    \n",
    "    except Exception as e: return P(f\"Refund failed: {str(e)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68e43376",
   "metadata": {},
   "source": [
    "In order to use a refund capability we need an account management page where users can request refunds for their payments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6b56c0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "@rt(\"/account\")\n",
    "def account_management(sess):\n",
    "    user_email = sess['auth']\n",
    "    user_payments = payments(\"email=?\", (user_email,))\n",
    "    # Create table rows for each payment\n",
    "    payment_rows = []\n",
    "    for payment in user_payments:\n",
    "        action_button = \"\"\n",
    "        if payment.payment_status == 'paid':\n",
    "            action_button = Button(\"Request Refund\", hx_post=f\"/refund?checkout_sid={payment.checkout_session_id}\",hx_target=\"#refund-status\")\n",
    "        elif payment.payment_status == 'refunded': action_button = \"Refunded\"\n",
    "        \n",
    "        # Add row to table\n",
    "        payment_rows.append(\n",
    "            Tr(*map(Td, (payment.created_at, payment.amount, payment.payment_status, action_button))))\n",
    "    \n",
    "    # Create payment history table\n",
    "    payment_history = Table(\n",
    "        Thead(Tr(*map(Th, (\"Date\", \"Amount\", \"Status\", \"Action\")))),\n",
    "        Tbody(*payment_rows))\n",
    "    \n",
    "    return Titled(\n",
    "        \"Account Management\",\n",
    "        Div(H2(f\"Account: {user_email}\"),\n",
    "            H3(\"Payment History\"),\n",
    "            payment_history,\n",
    "            Div(id=\"refund-status\"),  # Target for refund status messages\n",
    "            A(\"Back to Home\", href=\"/\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a5aa7bd",
   "metadata": {},
   "source": [
    "When you initiate a refund, you can see the status of the refund in your Stripe dasbhoard at [`https://dashboard.stripe.com/payments`](https://dashboard.stripe.com/payments), or [`https://dashboard.stripe.com/test/payments`](https://dashboard.stripe.com/test/payments) if you are in `Test mode`\n",
    "\n",
    "It will look like this with a `Refunded icon`:\n",
    "    \n",
    "![](refund.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "626c26d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exports\n",
    "#| hide\n",
    "serve()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56643043",
   "metadata": {},
   "source": [
    "# Recap\n",
    "\n",
    "In this tutorial, we learned how to implement and test a complete Stripe payment flow including:\n",
    "\n",
    "1. Creating test products and prices\n",
    "2. Setting up a payment page and checkout session\n",
    "3. Webhook handling for secure payment verification\n",
    "4. Building success/cancel pages for the user experience\n",
    "5. Adding refund functionality\n",
    "6. Creating an account management page to view payment history\n",
    "\n",
    "When migrating this payment system to production, you'll need to create actual products, prices and webhooks in your Stripe dashboard rather than test ones. You'll also need to replace your test API keys with live Stripe API keys."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8937835a",
   "metadata": {},
   "source": [
    "## Cleanup -"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72e8d9b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from nbdev.export import nb_export"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6acad20c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "nb_export('Stripe.ipynb', lib_path='.', name='stripe_otp')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f208a50",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "archive_price(app_nm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d7384d7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
